#!/usr/bin/env python3
import http.client
import json
import base64


def get_file_content(owner, repo, path, access_token, ref):
    '''
    获取仓库具体路径下的内容
    https://docs.gitcode.com/docs/apis/get-api-v-5-repos-owner-repo-contents-path
    '''

    conn = http.client.HTTPSConnection("api.gitcode.com")
    payload = ''
    headers = {
    'Accept': 'application/json'
    }
    conn.request("GET", f"/api/v5/repos/{owner}/{repo}/contents/{path}?access_token={access_token}&ref={ref}", payload, headers)
    res = conn.getresponse()
    data = res.read()
    #print(data.decode("utf-8"))
    return data.decode("utf-8")

def update_file(owner, repo, path, access_token, data):
    '''
    更新文件
    https://docs.gitcode.com/docs/apis/put-api-v-5-repos-owner-repo-contents-path
    '''

    conn = http.client.HTTPSConnection("api.gitcode.com")
    payload = json.dumps({
    "content": base64.b64encode(data["content"].encode("utf-8")).decode("utf-8"),
    "sha": data["sha"],
    "branch": data["branch"],
    "message": data["message"],
    "author[name]": data["author_name"],
    "author[email]": data["author_email"]
    })
    headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
    }
    conn.request("PUT", f"/api/v5/repos/{owner}/{repo}/contents/{path}?access_token={access_token}", payload, headers)
    res = conn.getresponse()
    data = res.read()
    #print(data.decode("utf-8"))
    return data.decode("utf-8")

def find_bottle_insert_position(formula_content: str) -> int:
    """
    返回 `bottle do...end` 应该插入的行号（从 0 开始）。
    如果已有 `bottle do`，返回 -1（表示需要替换）。
    """
    lines = formula_content.splitlines()
    last_def_line = -1
    head_or_patch_line = -1

    for i, line in enumerate(lines):
        # 检查是否已有 bottle 块
        if line.strip().startswith("bottle do"):
            return -1
        
        # 记录最后一个 def 方法（如 def install, def test）
        if line.strip().startswith("def "):
            last_def_line = i
        
        # 检查 head 或 patch 块（bottle 应该插在它们之前）
        if line.strip() in ("head", "patch") and head_or_patch_line == -1:
            head_or_patch_line = i
    
    # 优先插入到最后一个 def 之后
    if last_def_line != -1:
        return last_def_line + 1
    
    # 其次插入到 head/patch 之前
    if head_or_patch_line != -1:
        return head_or_patch_line
    
    # 默认插入到文件末尾
    return len(lines)


def modify_file(content, position, add_content):
    lines = content.splitlines(keepends=True)
    lines.insert(position, f"{add_content}\n")
    return "".join(lines)


if __name__ == "__main__":
    print("测试:")
